import { Box, Icon, Input, Select, Switch } from '@alifd/next';
import { forwardRef } from 'react';
import { FormattedMessage } from 'react-intl';
import st from './index.module.scss';

interface ParamsValue {
  key?: string;
  value?: string;
}

interface Props {
  value?: ParamsValue[];
  defaultValue?: ParamsValue[];
  onChange?: (value: ParamsValue[]) => void;
}

const ParamsItem = ({ value = [{}], onChange, defaultValue = [{}] }: Props, ref) => {
  const addItem = () => {
    onChange && onChange(value.concat(defaultValue));
  };

  const deleteItem = (i: number) => {
    value.splice(i, 1);
    onChange && onChange([...value]);
  };

  const changeItem = (i: number, val: string, key = 'key') => {
    const newVal = [...value];
    newVal[i][key] = val;
    onChange && onChange([...newVal]);
  };

  return (
    <Box spacing={10} className={st.Params} ref={ref}>
      {value.map((item, i) => (
        <Box spacing={10} direction="row" key={i}>
          <Input style={{ width: 100 }} placeholder="参数名称" value={item.key} onChange={(val) => changeItem(i, val, 'key')} />
          <span>:</span>
          <Input hasClear placeholder="参数值" value={item.value} onChange={(val) => changeItem(i, val, 'value')} />
          <Icon type="error" onClick={() => deleteItem(i)} />
        </Box>
      ))}
      <div className={st.addBtn} onClick={addItem}>
        <Icon type="add" className={st.icon} size="xs" />
        <FormattedMessage id="commodity.add.parameter" />
      </div>
    </Box>
  );
};

export default forwardRef(ParamsItem);
